<template>
  <div>
    <!-- 1、顶部导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.go(-1)" />
    <!-- 2、搜索框 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="$router.push({ path: '/searchResult', query: { value } })"
      @input="onInput"
    >
      <!-- @search="onSearch" -->
      <template #action>
        <div @click="$router.push({ path: '/searchResult', query: { value } })">
          搜索
        </div>
      </template>
    </van-search>
    <!-- 3、展示模糊搜索内容 -->
    <van-cell
      :title="item"
      icon="search"
      v-for="(item, index) in showClolr"
      :key="index"
    >
      <template #title>
        <div
          v-html="item"
          @click="
            $router.push({
              path: '/searchResult',
              query: { value: suggestion[index] },
            })
          "
        ></div>
      </template>
    </van-cell>
    <!-- 4、历史记录 -->
    <van-cell title="历史记录" />
    <!-- <van-cell title="单元格"> -->
    <!-- 使用 right-icon 插槽来自定义右侧图标 -->
    <!-- <template #right-icon>
        <van-icon name="close" class="search-icon" />
      </template> -->
    <!-- </van-cell> -->
    <van-cell :title="item" v-for="(item, index) in history" :key="index">
      <!-- 使用 right-icon 插槽来自定义右侧图标 -->
      <template #right-icon>
        <van-icon name="close" class="search-icon" @click="iconBtn" />
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestion, searchHistory, delSearchHistory } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "",
      suggestion: [],
      timeID: null,
      history: [],
    };
  },
  methods: {
    // async onSearch() {
    //   //   回车或者点击搜索
    //   console.log(this.value);
    //   let res = await getSearch({ q: this.value });
    //   console.log(res);
    // },
    //删除历史记录
    async iconBtn() {
      let res = await delSearchHistory();
      console.log(res);
      this.history = res.data.data;
    },
    //模糊搜索
    onInput() {
      clearTimeout(this.timeID);
      this.timeID = setTimeout(async () => {
        if (this.value == "") {
          this.suggestion = [];
          return;
        }
        let res = await getSuggestion({ q: this.value });
        console.log(res);
        this.suggestion = res.data.data.options;
      }, 300);
    },
  },
  //计算属性
  computed: {
    showClolr() {
      let reg = new RegExp(this.value, "gi");
      return this.suggestion.map((item) =>
        item.replace(reg, (match) => `<span style="color:red">${match}</span>`)
      );
    },
  },
  async created() {
    let res = await searchHistory();
    console.log(res);
    this.history = res.data.data.keywords;
    // console.log(JSON.stringify(res));
  },
};
</script>

<style>
</style>